# encoding:utf-8
# ! /usr/bin/python
# filename: flaskExecutor.py
'''
该类定义TOSCA YAML语法树里部分使用到的关键字
'''
import sys
sys.path.append('..')
import json

from source.dao.countAlarms import CountAlarms
from flask import Flask, request, Response
# gevent
from gevent import monkey
from gevent.pywsgi import WSGIServer
from source.all_monitor_parallel.meterManagerParallel import MeterManagerParallel
monkey.patch_all()
# gevent end
app = Flask(__name__)


@app.route('/v2/meters', methods=['GET'])
def get_meter_stats():
    resource_id = request.args.get('resource_id')
    meters = [MeterManagerParallel().getMetricsRest(resource_id)]

    headers = {"Access-Control-Allow-Origin": "*",
               "Access-Control-Allow-Headers":
                   "Origin, X-Requested-With, Content-Type, Accept, X-ID, X-TOKEN, X-ANY-YOUR-CUSTOM-HEADER",
               "Access-Control-Allow-Methods": "POST, PUT, GET, OPTIONS, DELETE"}
    return Response(json.dumps(meters), mimetype='application/json', headers=headers)

@app.route('/v2/getAlarmsNum', methods=['GET'])
def get_alarm_num():
    resource_id = str(request.args.get('resource_id'))
    if not resource_id:
        return "can not found resource_id in the parameters"

    res_list = resource_id.split("!")
    ret_list = []

    for res in res_list:
        meters = {
            'resource_id': resource_id,
            'alarm_nums': '-1'
        }
        meters['resource_id'] = res
        meters.update(CountAlarms().getCurAlarm(res))
        ret_list.append(meters)

    headers = {"Access-Control-Allow-Origin": "*",
               "Access-Control-Allow-Headers":
                   "Origin, X-Requested-With, Content-Type, Accept, X-ID, X-TOKEN, X-ANY-YOUR-CUSTOM-HEADER",
               "Access-Control-Allow-Methods": "POST, PUT, GET, OPTIONS, DELETE"}

    return Response(json.dumps(ret_list), mimetype='application/json', headers=headers)

if __name__ == '__main__':
    #app.run(host="0.0.0.0", port=int(6688))
    http_server = WSGIServer(('0.0.0.0', 6688), app)
    http_server.serve_forever()
